package com.sqfw.project.zj.service.impl;

import com.sqfw.common.exception.BusinessException;
import com.sqfw.common.utils.SecurityUtils;
import com.sqfw.common.utils.StringUtils;
import com.sqfw.project.system.domain.SysUser;
import com.sqfw.project.system.mapper.SysUserMapper;
import com.sqfw.project.wp.domain.SysCode;
import com.sqfw.project.wp.domain.WpHandleLog;
import com.sqfw.project.wp.domain.WpVisitInfo;
import com.sqfw.project.wp.mapper.*;
import com.sqfw.project.zj.domain.ZjRecord;
import com.sqfw.project.zj.domain.ZjSoundCase;
import com.sqfw.project.zj.domain.ZjSoundCollect;
import com.sqfw.project.zj.mapper.ZjRecordMapper;
import com.sqfw.project.zj.mapper.ZjSoundCaseMapper;
import com.sqfw.project.zj.mapper.ZjSoundCollectMapper;
import com.sqfw.project.zj.service.IZjSoundCaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 声音案例service
 *
 * @author sudenghui
 * @date 2023-06-26
 */
@Service
public class ZjSoundCaseServiceImpl implements IZjSoundCaseService {

    @Autowired
    private ZjSoundCaseMapper zjSoundCaseMapper;

    @Autowired
    private ZjRecordMapper zjRecordMapper;

    @Autowired
    private SysCodeMapper sysCodeMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private WpVisitInfoMapper wpVisitInfoMapper;

    @Autowired
    private WpHandleLogMapper wpHandleLogMapper;

    @Autowired
    private ZjSoundCollectMapper zjSoundCollectMapper;


    /**
     * 新增一条声音案例
     *
     * @param zjSoundCase 声音案例
     * @return int 结果
     */
    public int addZjSoundCase(ZjSoundCase zjSoundCase) {

        ZjSoundCase soundCase = new ZjSoundCase();
        soundCase.setWpid(zjSoundCase.getWpid());
        List<ZjSoundCase> zjSoundCases = zjSoundCaseMapper.selectZjSoundCaseList(soundCase);
        if (zjSoundCases.size() > 0) {
            throw new BusinessException("500","该工单已经是声音案例，无法重复添加");

        }

        // todo 插入轨迹表
        int result = zjSoundCaseMapper.addZjSoundCase(zjSoundCase);
        return result;
    }


    /**
     * 查询声音案例列表
     * （声音案例待受理查询页面列表）
     *
     * @param zjSoundCase 声音案例
     * @return 声音案例集合
     */
    public List<ZjSoundCase> qryZjSoundCaseList(ZjSoundCase zjSoundCase) throws ParseException {

        List<String> districtAll = zjSoundCase.getDistrictAll();
        //居委会查询
        if (StringUtils.isNotEmpty(districtAll)) {
            for (int i = 0; i < districtAll.size(); i++) {
                if (i == 0) {
                    //区域
                    zjSoundCase.setDistrict(districtAll.get(i));
                }
                if (i == 1) {
                    //街道
                    zjSoundCase.setStreet(districtAll.get(i));
                }
                if (i == 2) {
                    //居委会
                    zjSoundCase.setCommittee(districtAll.get(i));

                }
            }
        }
        List<List<String>> classAllFind = zjSoundCase.getClassAllFind();
        //内容类别查询
        if (classAllFind == null || classAllFind.size() == 0) {
            zjSoundCase.setClassAll(null);
        } else {
            List<String> classAllCon = new ArrayList<>();
            for (List<String> strings : classAllFind) {
                classAllCon.add(strings.get(strings.size() - 1));
            }
            zjSoundCase.setClassAll(classAllCon);
        }
        List<ZjSoundCase> caseList = new ArrayList<>();
        // List<ZjSoundCase> zjSoundCases = zjSoundCaseMapper.qryZjSoundCaseList(zjSoundCase);

        if (StringUtils.isNotEmpty(zjSoundCase.getCollectStatus()) && StringUtils.isNotEmpty(zjSoundCase.getCollectCode())) {
            //我的收藏查询
            zjSoundCase.setCollectStatus("1");
            caseList = zjSoundCaseMapper.selectZjSoundCollectAndCaseList(zjSoundCase);

        }else {
            //普通查询
            caseList = zjSoundCaseMapper.selectZjSoundCaseList(zjSoundCase);
        }

        for (ZjSoundCase soundCase : caseList) {
            soundCase.setSubmitTime(soundCase.getCreateTime());
            String class1 = soundCase.getClass1();
            String class2 = soundCase.getClass2();
            String class3 = soundCase.getClass3();
            String class4 = soundCase.getClass4();
            SysUser sysUser = userMapper.selectUserByCode(soundCase.getCreateBy());
            soundCase.setSubmitName(sysUser.getNickName());
            StringBuffer name = new StringBuffer();

            if (StringUtils.isNotEmpty(class1)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class1));
                if (sysCode != null) {
                    soundCase.setMainNodename(sysCode.getNodename());
                }
            }

            if (StringUtils.isNotEmpty(class2)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class2));
                if (sysCode != null) {
                    name.append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class3)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class3));
                if (sysCode != null) {
                    name.append("/").append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class4)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class4));
                if (sysCode != null) {
                    name.append("/").append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(name)) {
                soundCase.setChildNodeName(name.toString());
            }
        }

        return caseList;
    }

    /**
     * 查看声音案例
     * （声音案例待受理页面的操作-处理、查看）
     *
     * @param sid 声音案例id
     * @return ZjSoundCase 声音案例对象
     */
    @Override
    public ZjSoundCase qryZjSoundCaseBySid(Long sid) {
        ZjSoundCase zjSoundCase = zjSoundCaseMapper.selectZjSoundCaseBySid(sid);
        ZjRecord zjRecord = new ZjRecord();
        zjRecord.setWpid(zjSoundCase.getWpid());
        List<ZjRecord> zjRecords = zjRecordMapper.selectZjRecordListByWpid(zjRecord);
        //List<String> recordAddrs = zjRecords.stream().map(ZjRecord::getRecordFilepath).collect(Collectors.toList());
        zjSoundCase.setRecordAddrs(zjRecords);

        WpHandleLog wpHandleLog = new WpHandleLog();
        wpHandleLog.setWpid(zjSoundCase.getWpid());
        List<WpHandleLog> wpHandleLogs = wpHandleLogMapper.selectWpHandleLogList(wpHandleLog);

        //循环轨迹表，赋值满意度等字段
        for (WpHandleLog handleLog : wpHandleLogs) {
            SysUser user = userMapper.selectUserByCode(handleLog.getOperator());
            handleLog.setNickName(user.getNickName());
            if ("承办单位处理".equals(handleLog.getLastState())) {
                zjSoundCase.setSatisfied(handleLog.getSatisfied());
                zjSoundCase.setReasonable(handleLog.getReasonable());
                zjSoundCase.setSolved(handleLog.getSolved());
            }
            if ("工单回userName = \"SQJLP3058\"访".equals(handleLog.getLastState())) {

                WpVisitInfo wpVisitInfo = wpVisitInfoMapper.selectWpVisitInfoByWpid(zjSoundCase.getWpid());

                zjSoundCase.setAcceptVisit(wpVisitInfo.getAcceptVisit());
                zjSoundCase.setIsanswer(wpVisitInfo.getIsanswer());
                zjSoundCase.setIssatisfied(wpVisitInfo.getIssatisfied());
                zjSoundCase.setIssatisfiedReason(wpVisitInfo.getIssatisfiedReason());
                zjSoundCase.setIssatisfiedOther(wpVisitInfo.getIssatisfiedOther());
                zjSoundCase.setIsReply(wpVisitInfo.getIsReply());
            }
        }
        zjSoundCase.setWpHandleLogs(wpHandleLogs);
        // System.out.println(zjSoundCase);
        return zjSoundCase;
    }

    /**
     * 修改声音案例
     * （声音案例待受理页面-处理后保存）
     *
     * @param zjSoundCase 声音案例
     * @return 结果
     */
    @Override
    public int updateZjSoundCase(ZjSoundCase zjSoundCase) {
        String code = SecurityUtils.getLoginUser().getUser().getCode();
        zjSoundCase.setUpdateBy(code);
        zjSoundCase.setUpdateTime(new Date());
        zjSoundCase.setReviewedBy(code);
        String followOperation = zjSoundCase.getFollowOperation();
        if ("审核通过".equals(followOperation)) zjSoundCase.setAcceptStatus("已采纳");
        if ("退回坐席".equals(followOperation)) zjSoundCase.setAcceptStatus("不采纳");
        return zjSoundCaseMapper.updateZjSoundCase(zjSoundCase);
    }

    /**
     * 根据工单号删除声音案例
     *
     * @param wpid 工单号
     * @return 结果
     */
    @Override
    public int delZjSoundCaseByWpid(String wpid) {
        return zjSoundCaseMapper.delZjSoundCaseByWpid(wpid);
    }

    /**
     * 查询已采纳声音案例列表
     * （声音案例已采纳页面列表）
     *
     * @param zjSoundCase 声音案例
     * @return 声音案例集合
     */
    @Override
    public List<ZjSoundCase> qryAcceptedZjSoundCaseList(ZjSoundCase zjSoundCase) {
        return zjSoundCaseMapper.qryAcceptedZjSoundCaseList(zjSoundCase);
    }

    /**
     * 查询我的所有声音案例
     * （默认展示不采纳和待采纳的信息（提交时间倒序排））
     *
     * @param zjSoundCase
     * @return 声音案例集合
     */
    @Override
    public List<ZjSoundCase> qryMyZjSoundCaseList(ZjSoundCase zjSoundCase) {
        zjSoundCase.setCollectStatus(null);
        zjSoundCase.setCollectCode(null);
        zjSoundCase.setCollectNickname(null);
        return zjSoundCaseMapper.qryMyZjSoundCaseList(zjSoundCase);
    }

    @Override
    public void updateCollectStatus(ZjSoundCase zjSoundCase) {

        ZjSoundCollect zjSoundCollect = new ZjSoundCollect();

        SysUser user = SecurityUtils.getLoginUser().getUser();
        zjSoundCollect.setCollectCode(user.getCode());
        zjSoundCollect.setCollectNickname(user.getNickName());

        ZjSoundCollect soundCollect = new ZjSoundCollect();
        soundCollect.setCaseId(zjSoundCase.getSid());
        soundCollect.setCollectCode(user.getCode());
        ZjSoundCollect collect =  zjSoundCollectMapper.selectZjSoundCollectByCaseId(soundCollect);
        zjSoundCollect.setCaseId(zjSoundCase.getSid());
        if ("1".equals(zjSoundCase.getCollectStatus())){

            zjSoundCollect.setCollectStatus("1");
            if (collect!=null){
                zjSoundCollect.setId(collect.getId());
                zjSoundCollect.setUpdateTime(new Date());
                zjSoundCollectMapper.updateZjSoundCollect(zjSoundCollect);
            }else {
                zjSoundCollect.setCreateTime(new Date());
                zjSoundCollectMapper.insertZjSoundCollect(zjSoundCollect);
            }
        }else if ("0".equals(zjSoundCase.getCollectStatus())){
            if (collect!=null){
                //取消收藏
                zjSoundCollect.setId(collect.getId());
                zjSoundCollect.setCollectStatus("0");
                zjSoundCollect.setUpdateTime(new Date());
                zjSoundCollectMapper.updateZjSoundCollect(zjSoundCollect);
            }

        }

    }

    @Override
    public void updateCollectDelFlag(ZjSoundCase zjSoundCase) {

        SysUser user = SecurityUtils.getLoginUser().getUser();
        zjSoundCase.setDeleteFlag("1");
        zjSoundCase.setUpdateTime(new Date());
        zjSoundCase.setUpdateBy(user.getNickName());
        zjSoundCaseMapper.updateCollectDelFlag(zjSoundCase);
    }


}
